package com.fashiontextile.designer.controller;

import com.fashiontextile.admin.entity.Dict;
import com.fashiontextile.admin.feign.AdminClient;
import com.fashiontextile.common.annotation.RequireRole;
import com.fashiontextile.common.constant.AppConstants;
import com.fashiontextile.common.constant.TokenConstants;
import com.fashiontextile.common.entity.LoginUser;
import com.fashiontextile.common.entity.R;
import com.fashiontextile.common.utils.AliyunOSSUtils;
import com.fashiontextile.common.utils.RedisUtils;
import com.fashiontextile.designer.entity.Designer;
import com.fashiontextile.designer.entity.DesignerWorks;
import com.fashiontextile.designer.entity.WorksAlbum;
import com.fashiontextile.designer.service.DesignerService;
import com.fashiontextile.user.entity.Comment;
import com.fashiontextile.user.entity.User;
import com.fashiontextile.user.feign.UserClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@AllArgsConstructor
public class DesignerController {
    private AdminClient adminClient;
    private UserClient userClient;
    private DesignerService designerService;
    private AliyunOSSUtils ossUtils;
    private RedisUtils redisUtils;
    private static final ObjectMapper mapper = new ObjectMapper();

    @PostMapping("")
    public R<?> registerDesigner(@RequestBody Designer designer,
                                 @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        User userInfo = userClient.getUserByUid(uid).getData();
        if (userInfo.getRole().getRid() != 3) {
            return R.fail("一名用户只能注册一个特殊角色");
        }
        designer.setUid(uid);
        Integer insertResult = designerService.insertDesigner(designer);
        boolean changeResult = userClient.changeRoleByUid(uid, 5).isSuccess();
        if (insertResult > 0 && changeResult) {
            LoginUser loginUser = (LoginUser) redisUtils.getObjectValue(TokenConstants.REDIS_PREFIX + uid);
            loginUser.setRole(AppConstants.ROLE_DESIGNER);
            redisUtils.setObjectValue(TokenConstants.REDIS_PREFIX + uid, loginUser);
            return R.success("注册成功");
        } else {
            return R.fail("注册失败");
        }
    }

    @PutMapping("")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> ModifyRegisterInfo(@RequestBody Designer newDesignerInfo,
                                   @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        Integer updateResult = designerService.updateDesignerInfo(newDesignerInfo, uid);
        return updateResult > 0 ? R.success("修改成功") : R.fail("修改失败");
    }

    @GetMapping("/me")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> getDesignerInfo(@RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        Designer designer = designerService.getDesignerByUid(uid);
        if (designer == null) {
            return R.fail("找不到该设计师");
        }
        return R.success(designer);
    }

    @PostMapping("/me/album")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> addAlbum(@RequestPart("worksAlbum") String worksAlbum,
                         @RequestPart(value = "picture", required = false) MultipartFile picture,
                         @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) throws Exception {
        WorksAlbum worksAlbum_ = mapper.readValue(worksAlbum, WorksAlbum.class);
        if (picture != null && !picture.isEmpty()) {
            String fileExtension = Objects.requireNonNull(picture.getOriginalFilename()).substring(picture.getOriginalFilename().lastIndexOf("."));
            String pictureUrl = (String) ossUtils.uploadMultipart(picture, UUID.randomUUID() + fileExtension).getData();
            worksAlbum_.setPicture(pictureUrl);
        }

        worksAlbum_.setFdid(designerService.getFdidByUid(uid));
        Integer addResult = designerService.addAlbum(worksAlbum_);
        return addResult > 0 ? R.success("添加成功") : R.fail("添加失败");
    }

    @PutMapping("/me/album")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> modifyAlbum(@RequestPart("worksAlbum") String worksAlbum,
                            @RequestPart(value = "worksAlbum", required = false) MultipartFile picture) throws Exception {
        WorksAlbum worksAlbum_ = mapper.readValue(worksAlbum, WorksAlbum.class);
        if (designerService.isExistAlbum(worksAlbum_.getWaid())) {
            if (picture != null && !picture.isEmpty()) {
                String fileExtension = Objects.requireNonNull(picture.getOriginalFilename()).substring(picture.getOriginalFilename().lastIndexOf("."));
                String pictureUrl = (String) ossUtils.uploadMultipart(picture, UUID.randomUUID() + fileExtension).getData();
                worksAlbum_.setPicture(pictureUrl);
            }
            Integer updateResult = designerService.updateAlbum(worksAlbum_);
            return updateResult > 0 ? R.success("修改成功") : R.fail("抱歉！修改失败，请联系管理员");
        } else {
            return R.fail("专辑不存在");
        }
    }

    @DeleteMapping("/me/album")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> deleteAlbum(long waid) {
        if (designerService.isExistAlbum(waid)) {
            Integer deleteResult = designerService.updataAlbumState(waid);
            return deleteResult > 0 ? R.success("删除成功") : R.fail("抱歉！删除失败，请联系管理员");
        } else {
            return R.fail("专辑不存在");
        }
    }

    @PostMapping("/me/album/{waid}/works")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> publishWorks(@PathVariable("waid") long waid,
                             @RequestBody DesignerWorks designerWorks,
                             @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        if (designerService.isExistAlbum(waid)) {
            // 设置设计师id
            designerWorks.setFdid(designerService.getFdidByUid(uid));

            // 设置专辑id
            WorksAlbum worksAlbum = new WorksAlbum();
            worksAlbum.setWaid(waid);
            designerWorks.setAlbum(worksAlbum);

            // 上传作品
            R<?> result = designerService.addDesignerWork(designerWorks);
            if (result.isSuccess()) {
                return R.success(result.getData(), "作品发布成功");
            }

            return R.fail("作品发布失败，请稍后重试");
        } else {
            return R.fail("专辑不存在");
        }
    }

    @PutMapping("/me/album/{waid}/works/{dwid}")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> modifyWorks(@PathVariable("waid") long waid, @PathVariable("dwid") long dwid, DesignerWorks designerWorks) {
        if (designerService.isExistAlbum(waid) && designerService.isExistWorks(waid)) {
            return designerService.updateWorksByDwid(designerWorks, dwid) ? R.success("修改成功") : R.fail("修改失败");
        } else {
            return R.fail("专辑或作品不存在");
        }
    }

    @DeleteMapping("/me/album/works/{dwid}")
    @RequireRole(AppConstants.ROLE_DESIGNER)
    public R<?> deleteWorks(@PathVariable("dwid") long dwid) {
        if (designerService.isExistWorks(dwid)) {
            Integer deleteResult = designerService.updataworksState(dwid);
            return deleteResult > 0 ? R.success("删除成功") : R.fail("抱歉！删除失败，请联系管理员");
        } else {
            return R.fail("作品不存在");
        }
    }

    @GetMapping("/id/{fdid}")
    public R<?> getDesigerInfo(@PathVariable("fdid") long fdid) {
        if (designerService.selectDesignerByid(fdid) == null) {
            return R.fail("找不到该设计师");
        } else {
            Designer designer = designerService.selectDesignerByid(fdid);
            Dict dict = adminClient.selectDict(designer.getEducation().getDid()).getData();
            designer.setEducation(dict);
            return R.success(designer);
        }
    }

    @GetMapping("/{fdid}/album")
    public R<?> getAllAlbumByFdid(@PathVariable("fdid") long fdid,
                                  @RequestParam(required = false, defaultValue = "1") Integer page) {
        if (designerService.selectDesignerByid(fdid) == null) {
            return R.fail("找不到该设计师");
        }
        PageHelper.startPage(page, 10);
        List<WorksAlbum> worksAlbumList = designerService.getAllAlbumByFdid(fdid);
        PageInfo<WorksAlbum> worksAlbums = new PageInfo<>(worksAlbumList);
        return R.success(worksAlbums);
    }

    @GetMapping("/album/{waid}")
    public R<?> getAlbumAndWorks(@PathVariable("waid") long waid) {
        if (designerService.getAlbumAndWorks(waid) == null) {
            return R.fail("找不到该专辑");
        }
        if (!designerService.isExistAlbum(waid)) {
            return R.fail("专辑已被删除，请联系管理员");
        }
        WorksAlbum worksAlbum = designerService.getAlbumAndWorks(waid);
        return R.success(worksAlbum);
    }

    @GetMapping("/works/{dwid}")
    public R<?> getWorks(@PathVariable("dwid") long dwid) {
        if (designerService.getWorksByDwid(dwid) == null) {
            return R.fail("找不到该作品");
        }
        if (!designerService.isExistWorks(dwid)) {
            return R.fail("作品已被删除，请联系管理员");
        }
        DesignerWorks dw = designerService.getWorksByDwid(dwid);
        return R.success(dw);
    }

    @GetMapping("")
    public R<?> getDesigners(Integer num, String type) {
        if (designerService.getDesigner(num, type) == null) {
            return R.fail("找不到该设计师");
        } else {
            return R.success(designerService.getDesigner(num, type));
        }
    }

    @GetMapping("/works")
    public R<?> getWorksS(String sort, @RequestParam(required = false, defaultValue = "1") Integer num) {
        return designerService.getWorksS(sort, num);
    }

    @PostMapping("/works/{dwid}/like")
    public R<?> ThumbsUpWorks(@PathVariable("dwid")Long dwid) {
        return designerService.addPopularity(dwid);
    }

    @PostMapping("/works/{dwid}/comment")
    public R<?> CommentWorks(@PathVariable("dwid") Long dwid, @RequestBody Comment comment,
                             @RequestHeader(TokenConstants.LOGIN_UID_HEADER) long uid) {
        return designerService.CommentWorks(dwid, comment, uid);
    }

    @GetMapping("/works/{dwid}/comment")
    public R<?> ShowWorksComment(@PathVariable("dwid") Long dwid) {
        return designerService.selectCommentByctid(dwid);
    }
}
